package com.xauto.pioneer.appuser.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.MainActivity;
import com.xauto.pioneer.appuser.activity.LoginActivity;
import com.xauto.pioneer.appuser.activity.takeCar.FoundCarActivity;
import com.xauto.pioneer.appuser.activity.user_aptitude.UsreAptitudeActivity;
import com.xauto.pioneer.appuser.adapter.ViewPagerAdapter;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.CarOrderInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.WebInfoCallBack;
import com.xauto.pioneer.appuser.model.CarOrderInfo;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.PageInfo;
import com.xauto.pioneer.appuser.model.ParkingSite;
import com.xauto.pioneer.appuser.model.ParkingSiteCar;
import com.xauto.pioneer.appuser.model.WebInfo;
import com.xauto.pioneer.appuser.util.DataCheckUtil;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.SerializeUtil;
import com.xauto.pioneer.appuser.util.ToastUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

/***
 *  网点车辆显示页面
 * @author Lemon Wed 1 Mar 14:02
 */
public class ParkingSiteCarDialog extends Dialog {
    protected int page = Constants.PAGE;
    private PromptDialog promptDialog;
    private Context mContext;
    private ViewPager viewPagerSiteCar;
    private ViewPagerAdapter adapter;
    /** viewpager 数据*/
    private List<View> views;
    /** 车辆列表数据*/
    private List<ParkingSiteCar> parkingSiteCars;
    /** 选中的取车网点*/
    private ParkingSite parkingSite;
    /** 选中的取车站名*/
    private String parkingSiteName="";
    /** 选中的取车精度*/
    private String parkingSiteLongNum="";
    /** 选中的取车纬度*/
    private String parkingSiteLatNum="";
    /** 用户精度*/
    private String UsserLongNum="";
    /** 用户纬度*/
    private String UsserLatNum="";
    /**取车点ID*/
    private String parkingSiteID;
    /*public ParkingSiteCarDialog(Context context, ParkingSite parkingSite) {
        super(context, R.style.MainLoadingDialogTheme);
        mContext = context;
        this.parkingSite = parkingSite;
        initView();
        initData();
    }*/
    public ParkingSiteCarDialog(Context context, String parkingSiteID,String Lat,String Long) {
        super(context, R.style.MainLoadingDialogTheme);
        mContext = context;
        this.parkingSiteID = parkingSiteID;
        this.UsserLongNum=Long;
        this.UsserLatNum=Lat;
        initView();
        initData();
    }
    protected void initView() {
        setContentView(R.layout.dialog_parking_site_car);
        getWindow().setGravity(Gravity.BOTTOM);
        getWindow().setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        promptDialog = new PromptDialog(mContext, mContext.getString(R.string.notice), mContext.getString(R.string.text_not_network),
                mContext.getString(R.string.to_setting), mContext.getString(R.string.logout),mContext.getString(R.string.dialogpic_notice), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去设置
                promptDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出
                promptDialog.dismiss();
            }
        });

        viewPagerSiteCar = (ViewPager) findViewById(R.id.viewPagerSiteCar);
    }

    protected void initData() {
        setCanceledOnTouchOutside(true);
        setCancelable(true);

        views = new ArrayList<>();
        adapter = new ViewPagerAdapter(mContext, views);
        viewPagerSiteCar.setAdapter(adapter);
        loadCarList();

    }

    /** 初始化 viewpager */
    private void initViewPager() {
        //清空View列表
        views.clear();
        for (int i = 0; i < parkingSiteCars.size(); i++) {
            final ParkingSiteCar car = parkingSiteCars.get(i);
            final View v = LayoutInflater.from(mContext).inflate(R.layout.item_parking_site_map_new, null);
            ImageView ivSiteMapCar = (ImageView) v.findViewById(R.id.ivSiteMapCar);
            TextView tvSiteMapCarName = (TextView) v.findViewById(R.id.tvSiteMapCarName);
            TextView tvSiteMapCarNum = (TextView) v.findViewById(R.id.tvSiteMapCarNum);
            TextView tvSiteMapDistance = (TextView) v.findViewById(R.id.tvSiteMapDistance);
            TextView tvSiteMapSatCount = (TextView) v.findViewById(R.id.tvSiteMapSatCount);
            TextView tvSiteMapCost = (TextView) v.findViewById(R.id.tvSiteMapCost);
            final TextView tvSiteMapCarName_control = (TextView) v.findViewById(R.id.tvSiteMapCarName_control);
            final TextView tvSiteMapTakeCar = (TextView) v.findViewById(R.id.tvSiteMapTakeCar);
            TextView ivSiteAdd= (TextView) v.findViewById(R.id.ivSiteAdd);
            TextView ivSitedistance= (TextView) v.findViewById(R.id.ivSitedistance);

            ImageView ivSiteMapPre= (ImageView) v.findViewById(R.id.ivSiteMapPre);
            ImageView ivSiteMapNext= (ImageView) v.findViewById(R.id.ivSiteMapNext);

            ImageLoader.getInstance().displayImage(car.car_image.thumb,ivSiteMapCar);
            if(car.is_control.is_control.equals("true")){
                tvSiteMapCarName_control.setVisibility(View.VISIBLE);
                tvSiteMapTakeCar.setVisibility(View.GONE);
                //tvSiteMapTakeCar.setClickable(false);
            }

            double distance = 0d;
            java.text.DecimalFormat   df=new   java.text.DecimalFormat("#.00");
            try {
                //计算当前位置到网点距离
                distance = DistanceUtil.getDistance(new LatLng(Double.valueOf(UsserLatNum), Double.valueOf(UsserLongNum)), new LatLng(Double.valueOf(parkingSiteLatNum),Double.valueOf(parkingSiteLongNum)));
            } catch (Exception e) {

            }
            //取车点距离
            ivSitedistance.setText(df.format(distance) +"米");
            ivSiteAdd.setText(parkingSiteName);
            tvSiteMapCarName.setText(car.car_series_name+" "+car.transmission_case_type_name);
            tvSiteMapCarNum.setText(car.plate_no);
            tvSiteMapDistance.setText(car.car_endurance_mileage+"公里");
            tvSiteMapSatCount.setText(car.seat_count+"座/"+car.car_structure_name);
            tvSiteMapCost.setText(car.billingRuleInfo.billing_rule_name);

            ivSiteMapPre.setVisibility(car.index == 0 ? View.INVISIBLE : View.VISIBLE);
            ivSiteMapNext.setVisibility(car.index + 1 == parkingSiteCars.size() ? View.INVISIBLE : View.VISIBLE);

            ivSiteMapPre.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //上一辆
                    viewPagerSiteCar.setCurrentItem(car.index - 1);
                }
            });
            ivSiteMapNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //下一辆
                    viewPagerSiteCar.setCurrentItem(car.index + 1);
                }
            });
            tvSiteMapTakeCar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //确定用车
                        if(DataCheckUtil.isLogin(mContext)) {
                            //判断是否审核通过，暂时未通过，进入审核流程
                            if (!DataCheckUtil.isAuthIdentity(mContext)){
                                mContext.startActivity(new Intent(mContext, UsreAptitudeActivity.class));
                              //  mContext.startActivity(new Intent(mContext, TakeCarVerifyActivity.class));
                            }else {
                                promptDialog = new PromptDialog(mContext, mContext.getString(R.string.now_take_car), mContext.getString(R.string.take_car_hint),
                                        "确定", "取消",mContext.getString(R.string.dialogpic_nopic), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        promptDialog.dismiss();
                                        dismiss();
                                        //TODO 确定事件
                                        final ParkingSiteCar parkingSiteCar = parkingSiteCars.get(viewPagerSiteCar.getCurrentItem());
                                        //开启车辆订单
                                        DataLoadUtil.startCarOrder(mContext, parkingSiteCar.car_no, new CarOrderInfoCallBack() {
                                            @Override
                                            public void getCarOrderInfo(CarOrderInfo carOrderInfo) {
                                                //跳转到寻找车辆页面 记录当前订单，防止意外退出APP
                                                if (carOrderInfo == null)return;
                                                PreferencesUtils.putString(mContext, Constants.KEY_SITE_CAR, SerializeUtil.serialize(parkingSiteCar));
                                                PreferencesUtils.putString(mContext, Constants.KEY_CAR_ORDER_INFO, SerializeUtil.serialize(carOrderInfo));
                                                FoundCarActivity.startAction(mContext,parkingSiteCar.plate_no,carOrderInfo.car_order_no,false);
                                            }
                                        });
                                    }
                                }, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        promptDialog.dismiss();
                                    }
                                });
                                promptDialog.show();
                            }
                        } else {
                            ToastUtil.showShort(mContext, "请先登录");
                            mContext.startActivity(new Intent(mContext, LoginActivity.class));
                        }
                }
            });
            v.findViewById(R.id.tvSiteMapCostBudget).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //费用预估 分为油车 电车
                    DataLoadUtil.getWebInfo(mContext, "8", "", car.car_no, new WebInfoCallBack() {
                        @Override
                        public void getWebInfo(final WebInfo webInfo) {
                            ((Activity)mContext).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    String title = car.billingRuleInfo.billing_rule_title;
//                                    String content = car.billingRuleInfo.billing_rule_content_url;
                                    String title = webInfo.data_value.title;
                                    String content = webInfo.data_value.content;
                                    promptDialog = new PromptDialog(mContext,"",content,
                                            "确定", "",mContext.getString(R.string.dialogpic_nopic),new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            promptDialog.dismiss();
                                        }
                                    },null,true,null);
                                    promptDialog.show();
                                }
                            });
                        }
                    });
                }
            });
            views.add(v);
            tvSiteMapCarName_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //费用预估 分为油车 电车
                DataLoadUtil.getWebInfo(mContext, "10", "", car.car_no, new WebInfoCallBack() {
                    @Override
                    public void getWebInfo(final WebInfo webInfo) {
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                    String title = car.billingRuleInfo.billing_rule_title;
//                                    String content = car.billingRuleInfo.billing_rule_content_url;
                                String title = webInfo.data_value.title;
                                String content = webInfo.data_value.content;
                                promptDialog = new PromptDialog(mContext,"",content,
                                        "确定", "", mContext.getString(R.string.dialogpic_nopic),new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        promptDialog.dismiss();
                                    }
                                },null,true,null);
                                promptDialog.show();
                            }
                        });
                    }
                });
            }
        });
    }
        adapter.notifyDataSetChanged();
    }

    /**
     * 获取车辆数据
     */
    private void loadCarList(){
        if (parkingSiteID == null) return;
        parkingSiteCars = new ArrayList<ParkingSiteCar>();
        new LHttpLib().getParkingSiteCarList(mContext,parkingSiteID, new PageInfo(page, Constants.COUNT),new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                parkingSiteName=jsonStatus.data.optString("site_name").toString();
                parkingSiteLatNum=jsonStatus.data.optString("site_longitude_num").toString();
                parkingSiteLongNum=jsonStatus.data.optString("site_latitude_num").toString();
                JSONArray jsonArray = jsonStatus.data.optJSONArray("car_list");
                if(jsonArray != null && jsonArray.length() > 0) {
                    parkingSiteCars.clear();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        parkingSiteCars.add(new ParkingSiteCar().parse(i,jsonArray.optJSONObject(i)));
                    }
                    ((MainActivity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initViewPager();
                        }
                    });
                }
            }
        });
    }


}
